package gitlab

import (
	"encoding/json"
	"fmt"

	gitlab "github.com/xanzy/go-gitlab"
)

var (
	git   *gitlab.Client
	token string = "YYccs6XJ-sYu4YQ9xG9p" //YOUR_GITLAB_TOKEN
	url   string = "https://xxx.xxx.xxx"  //YOUR_GITLAB_URL
)

func init() {
	var err error
	git, err = gitlab.NewClient(token, gitlab.WithBaseURL(url))
	if err != nil {
		fmt.Printf("initclienterr:%v\n", err)
		panic(err)
	} else {
		fmt.Println("初始化完成")
	}
}

func main() {
	//测试获取项目
	project, _ := GetAllProject()

	//test
	str, _ := json.Marshal(project)
	fmt.Println(string(str))
}

func GetAllProject() ([]*gitlab.Project, error) {
	lbo := &gitlab.ListProjectsOptions{ListOptions: gitlab.ListOptions{Page: 1, PerPage: 50}}
	var pro []*gitlab.Project
	for {
		p, _, err := git.Projects.ListProjects(lbo)
		if err != nil {
			fmt.Printf("list projects failed:%v\n", err)
			return nil, err
		}
		pro = append(pro, p...)
		if len(p) < 50 {
			break
		}
		lbo.ListOptions.Page++
	}
	return pro, nil
}
